<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>博客登陆页</title>

    <link rel="stylesheet" href="css/common.css">
    <link rel="stylesheet" href="css/login.css">

</head>

<body>
<div class="nav">
    <img src="pic/logo2.jpg" alt="">
    <span class="blog-title">我的博客系统</span>
    <div class="space"></div>
    <a class="nav-span" href="blog_list.html">主页</a>
    <a class="nav-span" href="javascript:;" onclick="checkLoginBeforeEdit()">写博客</a>
</div>

<div class="container-login">
    <div class="login-dialog">
        <h3>登陆</h3>
        <div class="row">
            <span>用户名</span>
            <input type="text" name="username" id="username">
        </div>
        <div class="row">
            <span>密码</span>
            <input type="password" name="password" id="password">
        </div>
        <div class="row">
            <button id="submit" onclick="login()">提交</button>
        </div>

    </div>
</div>
<script src="js/jquery.min.js"></script>
<script>
//校验登录状态，通过后再跳写博客页
    function checkLoginBeforeEdit() {
        // 获取本地存储的登录标识（和你登录成功时存储的 key 一致）
        const loginUserId = localStorage.getItem("loginUserId");
        const token = localStorage.getItem("token");

        // 未登录（无用户ID 或 无 token）
        if (!loginUserId || !token) {
            alert("请先登录后再写博客！"); // 弹出提示
            location.href = "blog_login.html"; // 跳转到登录页
            return;
        }

        // 已登录：正常跳转到写博客页面
        location.href = "blog_edit.html";
    }

        function login() {
            $.ajax({
                type:"post",
                url: "/user/login",
                contentType: "application/json",
                data: JSON.stringify({
                    userName: $("#username").val(),
                    password: $("#password").val()
                }),
                success:function(result){
                    if(result.code==200 && result.data!=null){
                        //用户登录成功
                        localStorage.setItem("loginUserId", result.data.userId);
                        localStorage.setItem("token", result.data.token);
                        location.href = "blog_list.html";
                    }else{
                        //TODO
                        alert(result.errMsg);
                    }
                }
            });
        }
    </script>
</body>

</html>